package juc.mysynchronized;

/**
 * @ClassName CountDownLatchExample
 * @PackageName juc.mysynchronized
 * @projectName myThread
 * @Description TODO
 * @Author games
 * @Date 2025/9/4 下午4:07
 * @Version 1.0
 */
import java.util.concurrent.CountDownLatch;

/**
 * 3. CountDownLatch（闭锁）
 * 应用场景：
 *
 * 并行任务同步：确保所有任务都完成后继续执行下一步操作。
 * 多任务汇总：确定所有线程已完成工作。
 * 资源初始化：等待资源初始化完成后再开始使用。
 *
 */
public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        int threadCount = 5;
        CountDownLatch latch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " is running.");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " has finished.");
                latch.countDown(); // 完成一个任务，计数减一
            }).start();
        }

        latch.await(); // 等待所有任务完成
        System.out.println("All threads have completed their tasks.");
    }
}
